/**
 * @file  DFRobot_PT100.cpp
 * @brief  Define the infrastructure of the DFRobot_PT100 class and the implementation of the underlying methods
 * @copyright   Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
 * @license     The MIT License (MIT)
 * @author      [lym](yiming.luo@dfrobot.com)
 * @version     V1.0.2
 * @date        2025-02-20
 * @url         https://github.com/DFRobot/DFRobot_PT100
 */

#include "DFRobot_PT100.h"

DFRobot_PT100::DFRobot_PT100()
{
    _voltageRef = 5.000;
}

DFRobot_PT100::DFRobot_PT100(float referenceVoltage)
{
    _voltageRef = referenceVoltage;
}

/**
 * @fn readTemperature
 * @brief get PT100 temperature
 * @param PIN analogPin
 * @return temperature
 */
int DFRobot_PT100::readTemperature(int PIN)
{
    int analogValue = analogRead(PIN);
    float voltage = 0, res = 0;
    voltage = analogValue * _voltageRef / (ADC_RESOLUTION * 1.0);
    res = (1800 * voltage + CALIBRATION_COEFFICIENT * 18) / (CALIBRATION_COEFFICIENT / 100.0 * 18 - voltage);
    int front = 0, end = 0, mid = 0;
    front = 0;
    end = 399;
    mid = (front + end) / 2;
    while (front < end && pgm_read_float(&PT100Tab[mid]) != res)
    {
        if (pgm_read_float(&PT100Tab[mid]) < res)
        {
            if (pgm_read_float(&PT100Tab[mid + 1]) < res)
                front = mid + 1;
            else
            {
                mid = _compareMidpointIndex(res, mid);
                return mid;
            }
        }
        if (pgm_read_float(&PT100Tab[mid]) > res)
        {
            if (pgm_read_float(&PT100Tab[mid - 1]) > res)
                end = mid - 1;
            else
            {
                mid = _compareMidpointIndex(res, mid - 1);
                return mid;
            }
        }
        mid = front + (end - front) / 2;
    }
    return mid;
}
int DFRobot_PT100::_compareMidpointIndex(float pt, int idx)
{
    if ((pt - pgm_read_float(&PT100Tab[idx])) > (pgm_read_float(&PT100Tab[idx + 1]) - pgm_read_float(&PT100Tab[idx])) / 2)
        return idx + 1;
    else
        return idx;
}
DFRobot_PT100::~DFRobot_PT100()
{
}